<template>
  <el-dialog top="20vh" :title="title" v-model="visible" :close-on-press-escape="false" :close-on-click-modal="false"
    @closed="clear">
    <el-container>
      <!-- 机构 -->
      <el-aside style="width: 200px;">
        <el-card shadow="never">
          <template #header>
            <div>
            <el-input placeholder="请输入机构名称过滤" v-model="filterText" />
          </div>
          </template>
          <div class="organ-scrollbar">
            <el-scrollbar>
              <el-tree ref="organTreeRef" :node-key="'id'" :data="treeOrgan"
                :props="{ label: 'name', children: 'children' }" :expand-on-click-node="false"
                :filter-node-method="filterNode" @node-click="clickNode">
              </el-tree>
            </el-scrollbar>
          </div>
        </el-card>
      </el-aside>

      <!-- 账户表格 -->
      <el-main>
        <!-- 搜索栏 -->
        <autumn-search :formModel="queryInfo" @search="search">
          <template #default>
            <el-form-item prop="name" label="姓名">
              <el-input v-model="queryInfo.name" />
            </el-form-item>
          </template>
        </autumn-search>

        <div class="task-table">
          <autumn-table ref="mainTableRef" :height="'10%;'" :page="page" @changePage="changePage">
            <template #button>
              <el-button type="primary" @click="apply">确定</el-button>
              <el-button type="info" @click="close">取消</el-button>
            </template>
            <template #column>
              <el-table-column type="selection" label="#" fixed="left" width="50" align="center" v-if="multiple" />
              <el-table-column label="#" fixed="left" width="50" align="center" v-else>
                <template #default="scope">
                  <el-radio :label="scope.$index" v-model="radioIndex">
                    <span></span>
                  </el-radio>
                </template>
              </el-table-column>
              <el-table-column prop="loginName" label="用户名" />
              <el-table-column prop="name" label="姓名" />
              <el-table-column label="性别">
                <template #default="scope">
                  <el-tag size="small" :type="scope.row.gender == 2 ? 'warning' : 'success'">{{ scope.row.gender == 2 ?
                      '女' : '男'
                  }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="email" label="邮箱" />
              <el-table-column prop="phone" label="联系方式" />
            </template>
          </autumn-table>
        </div>
      </el-main>
    </el-container>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import useTable from 'src/hooks/useTable'
import { pageAccount } from 'src/api/system/account'
import { listOrgan } from 'src/api/system/organ'

const { page, resetPage } = useTable()

const props = defineProps({
  multiple: {
    type: Boolean,
    default() {
      return false
    }
  },
  title: {
    type: String,
    default() {
      return ''
    }
  },
  defaultValue: {
    type: [String, Array],
    default: () => ''
  }
})

// 弹出窗
const visible = ref<boolean>(false)
const open = function () {
  visible.value = true
  search()
}
const close = function () {
  visible.value = false
}
const clear = function () {
  filterText.value = ''
  radioIndex.value = -1
  Object.assign(queryInfo, {
    organId: '',
    name: '',
    isEnable: '1'
  })
  resetPage()
  mainTableRef.value.$refs.dataTableRef.setCurrentRow()
  mainTableRef.value.$refs.dataTableRef.clearSelection()
}
defineExpose({
  open
})

// 查询机构
const treeOrgan = ref<Array<any>>([])
listOrgan().then(({ data }) => { treeOrgan.value = data })

const organTreeRef = ref()
const filterText = ref<string>('')
watch(filterText, (newVal) => organTreeRef.value.filter(newVal))

const filterNode = function (value: string, data: any, node: any) {
  if (!value) return true
  return node.label.indexOf(value) > -1
}
const clickNode = function (data: any, node: any, el: any) {
  queryInfo.organId = data.id
  search()
}

// 分页查询账户
const queryInfo = reactive({
  organId: '',
  name: '',
  isEnable: '1'
})
const radioIndex = ref<number>(-1)

const mainTableRef = ref()
const changePage = function (pageNumber: number, pageSize: number) {
  page.pageNumber = pageNumber
  page.pageSize = pageSize

  pageAccount({ ...queryInfo, pageNumber, pageSize }).then(({ data }) => {
    page.data = data.list
    page.total = data.total

    if (props.multiple) {
      const tempArray = props.defaultValue as Array<string>
      tempArray.forEach((value: any) => {
        const row = page.data.find((item: any) => item.id === value)
        if (!row) return
        mainTableRef.value.$refs.dataTableRef.toggleRowSelection(row, true)
      })
    } else {
      radioIndex.value = page.data.findIndex((item: any) => item.id === props.defaultValue)
    }
  })
}
const search = function () {
  changePage(1, 10)
}

// 确认
const emits = defineEmits(['apply'])
const apply = function () {
  let selection = []
  if (props.multiple) {
    selection = mainTableRef.value.$refs.dataTableRef.getSelectionRows()
  } else if (radioIndex.value >= 0) {
    selection.push(page.data[radioIndex.value])
  }
  if (selection.length === 0) {
    ElMessage.warning('请选择用户')
    return
  }
  emits('apply', selection)
  close()
}
</script>

<style lang="scss" scoped>
.organ-scrollbar {
  height: 33vh;

  :deep(.el-scrollbar__wrap) {
    overflow-x: hidden !important;
  }
}

.task-table {
  height: 27vh;
}
</style>
